package com.example.toolproject.demo.service;

import com.example.toolproject.demo.domain.User;
import com.example.toolproject.demo.service.serviceimpl.DataSearchServiceImpl;
import com.example.toolproject.demo.util.DatabaseBackups;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Date;

/**
 * @ClassName ScheduledService
 * @Description TODO    定时任务   按要求爬取景区客流量，来提供数据给前端画图表
 * @Author lvyongwei
 * @Date
**/
@Service
public class ScheduledService {

    @Autowired
    private DatabaseBackups databaseBackups;

    @Autowired
    private DataSearchService dataSearchService;

    /**
     * 日志
     */
    private Logger logger= LoggerFactory.getLogger(ScheduledService.class);

    /**
     * 定时器  -- 作用是每天晚上2:40调用python代码执行爬取去哪儿网全国5A景区信息，并插入数据库 tourist
     */
    @Scheduled(cron = "* 40 2 * * *")
    public void hello(){
        String[] arguments = new String[] {"python", "C:\\WLRH\\pa.py"};
        try {
            Process process = Runtime.getRuntime().exec(arguments);
            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream(),"GBK"));
            String line = null;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
            in.close();
            //java代码中的process.waitFor()返回值为0表示我们调用python脚本成功，
            //返回值为1表示调用python脚本失败，这和我们通常意义上见到的0与1定义正好相反
            int re = process.waitFor();
            if(re==0){
                logger.info("使用python爬取数据成功"+new Date());
            }else{
                logger.error("使用python爬取数据失败"+new Date());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 定时器  -- 作用是每天晚上2:00删除身份不是管理员或教师的人导入的文化资源信息
     */
    @Scheduled(cron = "01 00 2 * * *")
    public void deleteDataSearch(){
        logger.info("开始进行删除当天所有非管理员教师导入文化资源数据"+new Date());
        User user=new User();
        dataSearchService.deleteDataSearch(user);
        logger.info("执行完毕");
    }

    public static void main(String[] args) {
        User user=new User();
        DataSearchService dataSearchService=new DataSearchServiceImpl();
        dataSearchService.deleteDataSearch(user);
    }
}
